package com.base.component.ai.agent.core.base;

import java.io.Serializable;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.component.ai.agent.bo.ContextBO;
import com.base.component.ai.agent.bo.ContextParamBO;
import com.base.component.ai.platform.prompt.PromptTextService;
import com.base.core.head.dto.ai.MessageTextDTO;
import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.core.json.JsonException;
import com.gitee.magic.core.utils.ReflectUtils;

/**
 * Agent
 * 
 * @author zywei
 *
 */
public abstract class BaseChatTextAgent<MSG extends Serializable, CP extends ContextParamBO, PP>
		extends BaseChatAgent<MSG, MessageTextDTO, CP, PP> {

	@Autowired
	protected PromptTextService<CP, PP> promptTextService;

	///////////////////////////////

	public String executeText(ContextBO<MSG, CP, PP> context) {
		Component component = getClass().getAnnotation(Component.class);
		return executeText(context, component.value());
	}
	
	public <T> T executeText(ContextBO<MSG, CP, PP> context, Class<T> prototype) {
		return executeText(context,prototype,true);
	}

	public <T> T executeText(ContextBO<MSG, CP, PP> context, Class<T> prototype,Boolean isDefaultValue) {
		Component component = getClass().getAnnotation(Component.class);
		try {
			return executeText(context, component.value(),prototype);
		}catch(JsonException e) {
			if(isDefaultValue) {
				return ReflectUtils.newInstance(prototype);
			}else {
				throw new ApplicationException(e);
			}
		}
	}
	
	public void executeStream(ContextBO<MSG, CP, PP> context) {
		Component component = getClass().getAnnotation(Component.class);
		executeStream(context, component.value(),(s)->{
			context.getFrameConsumer().accept(s);
		}, (s)->{
		});
	}

	public void executeStream(ContextBO<MSG, CP, PP> context, Consumer<String> frameConsumer, Consumer<String> successedConsumer) {
		Component component = getClass().getAnnotation(Component.class);
		executeStream(context, component.value(),frameConsumer, successedConsumer);
	}
	
	public String executeText(ContextBO<MSG, CP, PP> context,String code) {
		return promptTextService.execute(context.getContextParam(), context.getPromptParam(), code);
	}

	public <T> T executeText(ContextBO<MSG, CP, PP> context,String code, Class<T> prototype) {
		return promptTextService.execute(context.getContextParam(), context.getPromptParam(), code,prototype);
	}

	public void executeStream(ContextBO<MSG, CP, PP> context,String code, Consumer<String> frameConsumer, Consumer<String> successedConsumer) {
		promptTextService.executeStream(context.getContextParam(), context.getPromptParam(), code,frameConsumer, successedConsumer);
	}
	
}
